import os
import subprocess
import schedule
import time
import pexpect
from threading import Thread

class FtpTransfer:
    def __init__(self, source, target, remote_user, remote_host, remote_path, password):
        self.source = source
        self.target = target
        self.remote_user = remote_user
        self.remote_host = remote_host
        self.remote_path = remote_path
        self.password = password

    def rsync_backup(self):
        try:
            # 构建 rsync 命令
            rsync_cmd = f"rsync -avz {self.source} {self.remote_user}@{self.remote_host}:{self.remote_path}/{self.target}"
            print(f"执行命令: {rsync_cmd}")

            # 启动 rsync 进程
            process = pexpect.spawn(rsync_cmd)

            # 设置日志输出，便于调试
            process.logfile = open('rsync_debug.log', 'wb')  # 日志记录到文件

            # 等待密码提示
            process.expect(r'password:', timeout=30)  # 设置合理的超时（30秒）

            # 发送密码
            process.sendline(self.password)
            print(f"匹配到密码提示，发送密码{self.password}")

            # 等待命令执行结束
            process.expect(pexpect.EOF, timeout=None)
            print(f"开始等待指令完成")

            # 获取输出结果
            result = process.before.decode('utf-8')
            print("备份结果：", result)

            # 检查进程的退出状态
            if process.exitstatus == 0:
                print("备份成功")
            else:
                print(f"备份失败，退出状态码: {process.exitstatus}")

        except pexpect.TIMEOUT:
            print("超时: 没有匹配到密码提示或命令执行未完成。")
        except pexpect.EOF:
            print("EOF 到达，命令执行结束。")
        except Exception as e:
            print(f"执行备份时出错: {e}")
        finally:
            process.close()

    def schedule_backup(self):
        # 使用线程避免阻塞主程序
        thread = Thread(target=self.rsync_backup)
        thread.daemon = True  # 设置守护线程，主程序退出时线程也会退出
        thread.start()

    def start_scheduler(self):
        # 设置定时任务，每天 14:56 执行一次备份任务
        schedule.every().day.at("04:00").do(self.schedule_backup)

        print("备份服务已启动，等待任务执行...")

        # 保持脚本运行
        while True:
            schedule.run_pending()
            time.sleep(1)


if __name__ == "__main__":
    # 测试数据
    source_path = "/data1/24MMResource/TestAudio"  # 本地源路径
    target_dir = "24MM_Audio"  # 远程目标目录
    remote_user = "gongxiang"  # 远程服务器用户名
    remote_host = "10.54.0.15"  # 远程服务器地址
    remote_path = "/home/gongxiang/asr/Boloo"  # 远程服务器路径
    password = "Wxry,wdrS@52"

    ftp_transfer = FtpTransfer(source_path, target_dir, remote_user, remote_host, remote_path, password)

    # # 启动定时任务
    ftp_transfer.start_scheduler()
    # ftp_transfer.rsync_backup()
